package cn.brian.modular.sys.service;

import cn.brian.modular.sys.entity.SysUser;
import cn.brian.modular.sys.mapper.SysUserMapper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;


/**
 *
 * A07_用户表表数据服务层接口实现类
 * 
 * @author 黄景华
 * @date 2018-03-21 03:37:21
 *
 */
@Service(value = "sysUserService")
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> {

    @Autowired
	private SysUserMapper sysUserMapper;

    @Autowired
	private RocketMQTemplate rocketMQTemplate;

	@Transactional(rollbackFor = Exception.class)
	public void deleteUserById(String userId) throws Exception {
		this.sysUserMapper.deleteRoleUserByUserId(userId);
	}

	/**
	 * 不分页查询
	 * @param sysUser
	 * @return
	 */
	public List<SysUser> listUserWithoutPage(SysUser sysUser) {
		return sysUserMapper.selectUserList(sysUser);
	}

	/**
	 * 新增用户
	 * @param sysUser
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor = Exception.class)
	public SysUser preSaveUser(SysUser sysUser) throws Exception {
		String tx_no = UUID.randomUUID().toString();
		//this.sysUserMapper.insert(sysUser);

		//将sysUser转成json
		JSONObject jsonObject =new JSONObject();
		jsonObject.put("sysUser",sysUser);
		jsonObject.put("tx_no",tx_no);
		jsonObject.put("dataobject",SysUser.class.getName());
		String jsonString = jsonObject.toJSONString();
		//生成message类型
		//TRANSACTION_ID 当前事务id
		//keys放业务主键
		//tags放操作操作类型 save,update,delete
		Message<String> message = MessageBuilder.withPayload(jsonString).setHeader(RocketMQHeaders.TRANSACTION_ID, tx_no).setHeader(RocketMQHeaders.TAGS, "save").setHeader(RocketMQHeaders.KEYS, sysUser.getUserId()).build();

		//发送一条事务消息
		/**
		 * String txProducerGroup 生产组
		 * String destination topic，
		 * Message<?> message, 消息内容
		 * Object arg 参数
		 */
		SendResult sendResult =rocketMQTemplate.sendMessageInTransaction("producer_group_txmsg_sys1","topic_txmsg",message,sysUser);

		System.out.printf("------ send Transactional msg body = %s , sendResult=%s %n",
				message.getPayload(), sendResult.getSendStatus());
		return sysUser;
	}


	@Transactional(rollbackFor = Exception.class)
	public void preSaveBatchUser(List<SysUser> userList) throws Exception {
		String tx_no = UUID.randomUUID().toString();
		//this.sysUserMapper.insert(sysUser);

		//将sysUser转成json
		JSONObject jsonObject =new JSONObject();
		jsonObject.put("sysUser",userList);
		jsonObject.put("tx_no",tx_no);
		jsonObject.put("dataobject",SysUser.class.getName());
		String jsonString = jsonObject.toJSONString();

		// 运行结果：2
		System.out.println(jsonString.getBytes("ISO8859-1").length);
		// 运行结果：4
		System.out.println(jsonString.getBytes("GB2312").length);
		// 运行结果：4
		System.out.println(jsonString.getBytes("GBK").length);
		// 运行结果：6
		System.out.println(jsonString.getBytes("UTF-8").length);
		//生成message类型
		//TRANSACTION_ID 当前事务id
		//keys放业务主键
		//tags放操作操作类型 save,update,delete
		Message<String> message = MessageBuilder.withPayload(jsonString).setHeader(RocketMQHeaders.TRANSACTION_ID, tx_no).setHeader(RocketMQHeaders.TAGS, "save").setHeader(RocketMQHeaders.KEYS, tx_no).build();

		//发送一条事务消息
		/**
		 * String txProducerGroup 生产组
		 * String destination topic，
		 * Message<?> message, 消息内容
		 * Object arg 参数
		 */
		SendResult sendResult =rocketMQTemplate.sendMessageInTransaction("producer_group_txmsg_sys2","topic_txmsg_batch2",message,null);

		System.out.printf("------ send Transactional msg body = %s , sendResult=%s %n",
				message.getPayload(), sendResult.getSendStatus());
	}

	@Transactional(rollbackFor = Exception.class)
	public void saveUser(List<SysUser> userList) throws Exception {
		this.saveBatch(userList);

	}

	@Transactional(rollbackFor = Exception.class)
	public SysUser saveBatchUser(SysUser sysUser) throws Exception {
		this.sysUserMapper.insert(sysUser);

		return sysUser;
	}
	@Transactional(rollbackFor = Exception.class)
	public SysUser updateUser(SysUser sysUser) throws Exception {


		this.sysUserMapper.updateById(sysUser);

		return sysUser;
	}
	/**
	 * 批量删除用户
	 * @param userIds
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteUser(String userIds) throws Exception {
		boolean flag = false;
		if (null != userIds && "" != userIds) {
			String[] userIdArray = userIds.split(",");

			SysUser sysUser = null;
			for (int i = 0; i < userIdArray.length; i++) {
				sysUser = new SysUser();
				sysUser.setUserId(userIdArray[i]);
				this.sysUserMapper.deleteById(userIdArray[i]);
				this.sysUserMapper.deleteRoleUserByUserId(userIdArray[i]);
				flag = true;
			}
		}
		return flag;
	}

	public SysUser findUserByUserId(String userId) throws Exception {
		SysUser sysUser = new SysUser();
		sysUser.setUserId(userId);
		return sysUserMapper.selectUserByLoginName(sysUser);
	}


}
